package com.hundun.hddeal.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.hundun.hddeal.config.AlipayConfig;
import com.hundun.hddeal.dao.PayMapper;
import com.hundun.hddeal.entity.AdUser;
import com.hundun.hddeal.entity.Pay;
import com.hundun.hddeal.response.Result;
import com.hundun.hddeal.response.ResultUtil;
import com.hundun.hddeal.service.AdUserService;
import com.hundun.hddeal.util.OrderIdUtil;
import com.hundun.hddeal.util.TokenUtilT;
import com.hundun.hddeal.vo.AdUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static org.assertj.core.util.DateUtil.now;

/**
 * @author 谢
 */
@Slf4j
@Controller
@RequestMapping("ad")
public class AlipayController {

    @Autowired
    AdUserService adUserService;
    @Autowired
    PayMapper payMapper;

    /**
     * 获取配置文件的信息
     */
    String app_id = AlipayConfig.app_id;
    String private_key = AlipayConfig.private_key;
    String notify_url = AlipayConfig.notify_url;
    String return_url = AlipayConfig.return_url;
    String url = AlipayConfig.url;
    String charset = AlipayConfig.charset;
    String format = AlipayConfig.format;
    String public_key = AlipayConfig.public_key;
    String signtype = AlipayConfig.signtype;


    /**
     * 同步跳转
     *
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/returnUrl")
    public Result returnUrl(HttpServletRequest request) throws Exception {
        // 获取支付宝GET过来反馈信息（官方固定代码）
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, public_key, charset, signtype); // 调用SDK验证签名

        // 返回界面
        if (signVerified) {
            log.info("前往支付成功页面");
        }else {
            log.info("前往支付失败页面");
        }

        log.info(String.valueOf(request.getParameterMap()));


        return ResultUtil.success();
    }

    /**
     * 支付宝服务器异步通知
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("notifyUrl")
    public void notifyUrl(HttpServletRequest request,HttpServletResponse httpResponse) throws Exception {
        // 获取支付宝GET过来反馈信息
        HashMap params = new HashMap();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, public_key, charset, signtype);
        // 验证成功 更新订单信息
        if (signVerified) {
            log.info("异步通知成功");
            // 商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            // 交易状态
            String trade_status = request.getParameter("trade_status");
            //获取金额
            String money=request.getParameter("total_amount");
            // 修改数据库
            if("TRADE_SUCCESS".equals(trade_status)){

              Pay pay=payMapper.selectByPrimaryKey(out_trade_no);
                if(pay.getStatus()!=4){
                    //支付成功则改状态为充值成功
                    pay.setStatus((byte)4);
                    payMapper.updateByPrimaryKeySelective(pay);
                    //往用户账号添加对应金额
                    adUserService.updateMoney(pay.getUserNames(),-Double.parseDouble(money));
                }

            }
            httpResponse.getWriter().println("success");
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } else {
            log.info("异步通知失败");
        }
    }


    /**
     * 支付请求
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("alipay")
    public Result doPost(@RequestBody AdUserVo adUserVo){
        String adUserId = TokenUtilT.getTokenById(adUserVo.getAdUserToken());
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if(adUser==null){
            return ResultUtil.error("用户不存在");
        }
        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成订单号
        String out_trade_no = OrderIdUtil.OrderNum();
        Pay pay = new Pay();
        pay.setMoney(adUserVo.getMoney());
        pay.setUserNames(adUser.getAdId());
        pay.setUserPhone(adUser.getAdPhone());
        pay.setCreateDate(now());
        pay.setPayWay("支付宝");
        pay.setPayNum(out_trade_no);
        pay.setStatus((byte)1);
        pay.setOrderType((byte)1);
        pay.setUserFz(adUser.getFz());
        pay.setUserName(adUser.getUserName());
        payMapper.insertSelective(pay);

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", app_id, private_key, "json", charset, public_key, "RSA2");

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


        //付款金额，必填
        String total_amount = String.valueOf(adUserVo.getMoney());
        //订单名称，必填
        String subject = "用户充值";
        //商品描述，可空
        String body = "用户充值";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\"10m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String form="";
        try {
            //调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.success(100,"操作成功",form);
    }
















}
